/*
 * @lc app=leetcode.cn id=501 lang=java
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.ArrayList;
import java.util.List;

class Solution {

    int count = 1;
    int maxCount = 1;
    TreeNode pre = null;
    List<Integer> list = new ArrayList<>();
    public int[] findMode(TreeNode root) {
        // 中序遍历
        inOrder(root);

        int[] res = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }

    private void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }

        inOrder(root.left);

        if(pre != null) {
            if(root.val == pre.val) {
                count++;
            } else {
                count = 1;
            }

            if(count > maxCount) {
                maxCount = count;
                list.clear();
                list.add(root.val);
            } else if(count == maxCount) {
                list.add(root.val);
            }
        } else {
            list.add(root.val);
        }

        pre = root;

        inOrder(root.right);
    }
}
// @lc code=end

